"use client";

import { commentApi } from '@/constants';
import { get, post, put, patch, del } from '@/util/api';

// 用户信息接口
export interface User {
  id: number;
  username: string;
  email?: string;
  avatar?: string;
  bio?: string;
  createdAt: string;
  updatedAt: string;
  role: number;
  isActive: boolean;
}

// 评论基本信息接口
export interface CommentBase {
  content: string;
  articleId: number;
  replyTo?: number | null; // 回复的评论ID
  isActive?: number; // 0禁用，1启用
}

// 评论响应接口
export interface Comment extends CommentBase {
  id: number;
  userId: number;
  username?: string;
  avatar?: string;
  articleTitle?: string;
  author?: User; // 作者信息
  likeCount?: number;
  artinfo?: { // 文章信息
    id: number;
    title: string;
  };
  createdAt: string;
  updatedAt: string;
  replyCount?: number;
  replies?: Comment[];
}

// 评论列表响应接口
export interface CommentListResponse {
  items: Comment[];
  total: number;
  page: number;
  pageSize: number;
  hasMore: boolean;
}

// 评论统计数据接口
export interface CommentStats {
  totalCount: number;
  pendingCount: number;
  approvedCount: number;
  rejectedCount: number;
  dailyTrend: Array<{
    date: string;
    count: number;
  }>;
  topArticles: Array<{
    articleId: number;
    articleTitle: string;
    commentCount: number;
  }>;
  topUsers: Array<{
    userId: number;
    username: string;
    commentCount: number;
  }>;
}

/**
 * 评论管理服务类
 * 封装所有评论相关的API调用
 */
class CommentService {
  /**
   * 获取评论列表
   * @param params 查询参数
   * @returns Promise<CommentListResponse>
   */
  async getCommentList(params?: {
    page?: number;
    pageSize?: number;
    keyword?: string;
    articleId?: number;
    userId?: number;
    status?: number;
    startDate?: string;
    endDate?: string;
    orderBy?: 'createdAt' | 'likeCount' | 'replyCount';
    orderDirection?: 'asc' | 'desc';
  }): Promise<CommentListResponse> {
    try {
      const response = await get(commentApi.LIST, { params });
      return (response.data || response) as unknown as CommentListResponse;
    } catch (error) {
      console.error('获取评论列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取评论详情
   * @param id 评论ID
   * @returns Promise<Comment>
   */
  async getCommentDetail(id: number): Promise<Comment> {
    try {
      const response = await get(commentApi.DETAIL(id));
      return (response.data || response) as unknown as Comment;
    } catch (error) {
      console.error(`获取评论详情失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 获取评论的回复列表
   * @param commentId 评论ID
   * @param params 查询参数
   * @returns Promise<CommentListResponse>
   */
  async getCommentReplies(commentId: number, params?: {
    page?: number;
    pageSize?: number;
    status?: number;
  }): Promise<CommentListResponse> {
    try {
      const response = await get(commentApi.REPLIES(commentId), { params });
      return (response.data || response) as unknown as CommentListResponse;
    } catch (error) {
      console.error(`获取评论回复失败 (评论ID: ${commentId}):`, error);
      throw error;
    }
  }

  /**
   * 更新评论状态
   * @param id 评论ID
   * @param status 状态值
   * @returns Promise<Comment>
   */
  async updateCommentStatus(id: number, status: number): Promise<Comment> {
    try {
      const response = await patch(commentApi.UPDATE_STATUS(id), { isActive: status });
      return (response.data || response) as unknown as Comment;
    } catch (error) {
      console.error(`更新评论状态失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 删除评论
   * @param id 评论ID
   * @param options 删除选项
   */
  async deleteComment(id: number, options?: {
    includeReplies?: boolean; // 是否同时删除回复
  }): Promise<void> {
    try {
      await del(commentApi.DELETE(id), { params: options });
    } catch (error) {
      console.error(`删除评论失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 批量操作评论
   * @param ids 评论ID数组
   * @param action 操作类型
   * @param data 额外数据
   * @returns Promise<any>
   */
  async batchOperateComments(ids: number[], action: string, data?: object): Promise<unknown> {
    try {
      const response = await patch(commentApi.BATCH_OPERATE, { ids, action, ...data } );
      return response.data || response;
    } catch (error) {
      console.error('批量操作评论失败:', error);
      throw error;
    }
  }

  /**
   * 回复评论
   * @param commentId 评论ID
   * @param replyData 回复数据
   * @returns Promise<Comment>
   */
  async replyToComment(commentId: number, replyData: { content: string }): Promise<Comment> {
    try {
      const response = await post(commentApi.REPLY(commentId), replyData);
      return (response.data || response) as unknown as Comment;
    } catch (error) {
      console.error(`回复评论失败 (评论ID: ${commentId}):`, error);
      throw error;
    }
  }

  /**
   * 屏蔽评论者
   * @param userId 用户ID
   * @returns Promise<void>
   */
  async blockCommenter(userId: number): Promise<void> {
    try {
      await patch(commentApi.BLOCK_USER(userId));
    } catch (error) {
      console.error(`屏蔽评论者失败 (用户ID: ${userId}):`, error);
      throw error;
    }
  }

  /**
   * 获取评论统计数据
   * @param params 查询参数
   * @returns Promise<CommentStats>
   */
  async getCommentStats(params?: {
    startDate?: string;
    endDate?: string;
  }): Promise<CommentStats> {
    try {
      const response = await get(commentApi.STATS, { params });
      return (response.data || response) as unknown as CommentStats;
    } catch (error) {
      console.error('获取评论统计数据失败:', error);
      throw error;
    }
  }

  /**
   * 审核评论
   * @param id 评论ID
   * @param approved 是否通过审核
   * @param reason 拒绝原因（如果未通过）
   * @returns Promise<Comment>
   */
  async reviewComment(id: number, approved: boolean, reason?: string): Promise<Comment> {
    try {
      const response = await patch(commentApi.REVIEW(id), {
        approved,
        reason,
      });
      return (response.data || response) as unknown as Comment;
    } catch (error) {
      console.error(`审核评论失败 (ID: ${id}):`, error);
      throw error;
    }
  }

  /**
   * 更新评论内容
   * @param id 评论ID
   * @param content 评论内容
   * @returns Promise<Comment>
   */
  async updateCommentContent(id: number, content: string): Promise<Comment> {
    try {
      const response = await put(commentApi.DETAIL(id), { content });
      return (response.data || response) as unknown as Comment;
    } catch (error) {
      console.error(`更新评论内容失败 (ID: ${id}):`, error);
      throw error;
    }
  }
}

// 导出评论服务实例
export const commentService = new CommentService();
export default commentService;